<?php
include_once ROOT_PATH . 'include/lib/Model.class.php';
/**
 *
 * 模块核心类
 *
 *
 * This is NOT a freeware, use is subject to license terms
 *
 * @copyright Copyright (C) 2005 - 2099 Cenwor Inc.
 * @license http://www.cenwor.com
 * @link http://www.jishigou.net
 * @author 狐狸<foxis@qq.com>
 * @version $Id: master.mod.php 3238 2013-04-02 10:01:28Z wuliyong $
 */

if(!defined('IN_JISHIGOU'))
{
	exit('invalid request');
}

class MasterObject
{

	var $Config=array();
	var $Get,$Post,$Files,$Request,$Cookie,$Session;


	var $DatabaseHandler;

	var $MemberHandler;



	var $Title='';

	var $MetaKeywords='';

	var $MetaDescription='';


	var $Position='';


	var $Module='index';


	var $Code='';
	var $All_company = array();
	var $Channels = array();
	var $Channel_enable;
	var $yxm_html='';
	var $yxm_title='';
	var $__is_public = null;
	var $hookall_temp = null;

	function MasterObject(&$config)
	{
		//GX 安全监测
		if (!empty($this->Code)&&!in_array($this->Code, get_class_methods($this))){
			$this->Messager("您访问的地址无效",null);
		}
		$this->Config = $config;
		$this->Get     = &$_GET;
		$this->Post    = &$_POST;


		$this->Module  = get_param('mod');



		if($this->Config['ipbanned_enable']) {
			$ipbanned=ConfigHandler::get('access','ipbanned');
			if(!empty($ipbanned) && preg_match("~^({$ipbanned})~",client_ip())) {
				$this->Messager("您的IP已经被禁止访问和注册。",null);
			}
			unset($ipbanned);
		}


		if(!jsg_getcookie('mobilegotopc') &&
				!in_array($this->Module, array('login','vote','event','qun','channel','talk','live', 'share', 'output', 'attach', 'async')) &&
				($_SERVER['HTTP_USER_AGENT'] == '' ||
						preg_match("/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile|iphone|android)/i",
								$_SERVER['HTTP_USER_AGENT']))) {
			if($_GET['setcookie'] == 1) {
				jsg_setcookie('mobilegotopc', 1, 86400);
			} else {
				$this->Messager('您现在正在用手机访问电脑版网页，为节省流量你可以选择其他方式访问','index.php?mod=login&code=goto');
			}
		}


		$this->DatabaseHandler = & Obj::registry('DatabaseHandler');

		include_once ROOT_PATH . 'include/lib/member.han.php';
		$uid = 0;
		$password = '';
		if(($authcode=jsg_getcookie('auth')))
		{
			list($password,$uid)=explode("\t",authcode($authcode,'DECODE'));
		}
		$this->MemberHandler=new MemberHandler();
		$MemberFields = $this->MemberHandler->FetchMember($uid,$password);
		if(118 == $MemberFields['role_id']) {
			$this->Messager("您已经被永久禁止访问。",null);
		}
		$this->__init_code();



		if($this->Config['visitState'] == 1){
			if(true !== JISHIGOU_FOUNDER) {
				$allowed_login = false;
				if($this->Config['visitIp']){
					$visitIp = str_replace('.','\.',$this->Config['visitIp']);

					if(preg_match("~^({$visitIp})~",client_ip())){
						$allowed_login = true;
					}
				}
				if($this->Config['allowed_visit_role_list']){
					$allowed_visit_role_list = explode(',',$this->Config['allowed_visit_role_list']);
					if(in_array($MemberFields['role_id'],$allowed_visit_role_list)){
						$allowed_login = true;
					}
				}
				if($this->Config['visitMember'] && MEMBER_ID > 0){
					$visitMember = explode(',',$this->Config['visitMember']);
					if(in_array($MemberFields['nickname'],$visitMember)){
						$allowed_login = true;
					}
				}
				#禁止访问的，也可以进入网站首页（启用简版登陆）、对外公告、登陆、注册和找回密码页面
				if(!$allowed_login){
					if(!$this->__is_public()){
						jsg_member_logout();
						$this->Messager("网站内部开放中，您所在的用户组（{$MemberFields['role_name']}）没有访问权限；",null);
					}
				}
			}
		}

		if(MEMBER_ID > 0 && $this->Config['email_must_be_true'] == 1 && $MemberFields['email_checked'] == 0 && true !== JISHIGOU_FOUNDER && !$this->Config['ldap_enable']){
			if(!$this->__is_public()) {
				$this->Messager('该网站需邮箱验证才能进行访问','index.php?mod=member&code=setverify&ids='.$MemberFields['uid']);
			}
		}

		$channels = jlogic('channel')->get_pub_channel();
		$this->Channel_enable = $channels['channel_enable'];
		$this->Channels = $channels['channels'];

		if($this->Config['seccode_enable'] && $this->Config['seccode_pub_key'] && $this->Config['seccode_pri_key']){
			$this->yxm_html = jlogic('seccode')->GetYXM();
			$this->yxm_title = jlogic('seccode')->TitleYXM();
		}
		if(false == $this->MemberHandler->HasPermission($this->Module,$this->Code) && !$this->__is_public()) {
			$this->Messager($this->MemberHandler->GetError(), null);
		}
		$this->Title=$this->MemberHandler->CurrentAction['name'];		Obj::register("MemberHandler", $this->MemberHandler);


		if($GLOBALS['_J']['config']['jsg_member_login_extract']) {
			$rets = jsg_member_login_extract();
			if($rets) {
				if(MEMBER_ID < 1) {
					$func = $rets['login_direct'];
				} else {
					$func = $rets['logout_direct'];
				}

				if($func && function_exists($func)) {
					$ret = $func();

					if($ret) {
						$this->Messager(null, $ret);
					}
				}
			}
		}


		define("FORMHASH",substr(md5(substr(time(), 0, -4).$this->Config['auth_key']),0,16));
		if($_SERVER['REQUEST_METHOD']=="POST") {
			if($this->Post["FORMHASH"]!=FORMHASH) {
			}
		}


		if($this->Config['extcredits_enable'])
		{

			if(MEMBER_ID>0 && jsg_getcookie('login_credits')+3600<time())
			{
				update_credits_by_action('login',MEMBER_ID);

				jsg_setcookie('login_credits',time(),3600);
			}
		}


		if($this->Config['sendmailday'] > 0 && MEMBER_ID>0){
			jtable('mailqueue')->del(MEMBER_ID);
		}

		if ($this->Config['site_domain'] != $_SERVER['HTTP_HOST'] && !get_param('__redirect__') && false === strpos($this->Config['site_domain'], '/')) {
			$redirect_url = $this->Config['site_url'] . '/index.php?__redirect__=1&' . $_SERVER['QUERY_STRING'];
			if (isset($_SERVER['JSG-PHP-RUN-MODE']) && $_SERVER['JSG-PHP-RUN-MODE'] == 'PHP-CLI')
			{

			}
			else
			{
				header('Location: '.$redirect_url);
				exit;
			}
		}

		if($this->Config['company_enable'] && ($config['companytree'] = ConfigHandler::get('companytree'))){
			foreach($config['companytree'] as $val){
				$this->All_company[] = array(
						'id'        => $val['id'],
						'name'      => $val['name'],
						'shortname' => cut_str($val['name'],16,'..'),
						'css'       => (($_GET['id'] == $val['id'] && $_GET['mod'] == 'company') ? 'hover ' : '').($val['step'] == '@' ? 'nav' : 'none')
				);
			}
		}

		if(!$GLOBALS['_J']['config']['acceleration_mode']) {
			$this->hookall_temp = $this->oldhookscript();
		}

		define("LEFTNAV",jsg_getcookie('leftnav'));
		define("TOPNOTICE",jsg_getcookie('topnotice'));


		$this->_initTheme((MEMBER_ID>0?$MemberFields:null));
	}


	function Messager($message, $redirectto='',$time = -1,$return_msg=false,$js=null)
	{
		global $rewriteHandler;

		ob_start();

		if ($time===-1)
		{
			$time=(is_numeric($this->Config['msg_time'])?$this->Config['msg_time']:5);
		}


		$to_title=($redirectto==='' or $redirectto==-1)?"返回上一页":"跳转到指定页面";

		if($redirectto===null)
		{
			$return_msg=$return_msg===false?"&nbsp;":$return_msg;
		}
		else
		{
			$redirectto=($redirectto!=='')?$redirectto:($from_referer=referer());
			if(str_exists($redirectto,'mod=login','code=register','/login','/register'))
			{
				$referer='&referer='.urlencode('index.php?'.$_SERVER['QUERY_STRING']);
				jsg_setcookie('referer','index.php?'.$_SERVER['QUERY_STRING']);
			}
			if (is_numeric($redirectto)!==false and $redirectto!==0)
			{
				if($time!==null){
					$url_redirect="<script language=\"JavaScript\" type=\"text/javascript\">\r\n";
					$url_redirect.=sprintf("window.setTimeout(\"history.go(%s)\",%s);\r\n",$redirectto,$time*1000);
					$url_redirect.="</script>\r\n";
				}
				$redirectto="javascript:history.go({$redirectto})";
			}
			else
			{
				if($rewriteHandler && null!==$message)
				{
					$redirectto .= $referer;
					if(!$from_referer && !$referer) {
						$redirectto=$rewriteHandler->formatURL($redirectto,true);
					}
				}

				if($message===null)
				{
					$redirectto=rawurldecode(stripslashes(($redirectto)));
					@header("Location: $redirectto"); #HEADER跳转
				}
				if($time!==null)
				{
					$url_redirect = ($redirectto?'<meta http-equiv="refresh" content="' . $time . '; URL=' . $redirectto . '">':null);
				}
			}
		}
		$title="消息提示:".(is_array($message)?implode(',',$message):$message);

		$title=strip_tags($title);
		if($js!="") {
			$js="<script language=\"JavaScript\" type=\"text/javascript\">{$js}</script>";
		}
		$additional_str = $url_redirect.$js;

		include(template('messager'));
		$body=ob_get_clean();

		$this->ShowBody($body);

		exit;
	}


	function _initTheme($uid=null)
	{
		$themes = 'themes';

		if(!$this->Config[$themes])
		{
			$this->Config[$themes] = array(
					'theme_id' => $this->Config['theme_id'],
					'theme_bg_image' => $this->Config['theme_bg_image'],
					'theme_bg_color' => $this->Config['theme_bg_color'],
					'theme_text_color' => $this->Config['theme_text_color'],
					'theme_link_color' => $this->Config['theme_link_color'],
					'theme_bg_image_type' => $this->Config['theme_bg_image_type'],
					'theme_bg_repeat' => $this->Config['theme_bg_repeat'],
					'theme_bg_fixed' => $this->Config['theme_bg_fixed'],
			);
		}

		if($uid)
		{
			$this->Config['theme_id'] = $this->Config[$themes]['theme_id'];
			$this->Config['theme_bg_image'] = $this->Config[$themes]['theme_bg_image'];
			$this->Config['theme_bg_color'] = $this->Config[$themes]['theme_bg_color'];
			$this->Config['theme_text_color'] = $this->Config[$themes]['theme_text_color'];
			$this->Config['theme_link_color'] = $this->Config[$themes]['theme_link_color'];
			$this->Config['theme_bg_position'] = $this->Config[$themes]['theme_bg_image_type'];
			$this->Config['theme_bg_repeat'] = $this->Config[$themes]['theme_bg_repeat'];
			$this->Config['theme_bg_fixed'] = $this->Config[$themes]['theme_bg_fixed'];


			$_my = array();
			if (is_array($uid))
			{
				$_my = $uid;
			}
			else
			{
				$uid = max(0,(int) ($uid ? $uid : MEMBER_ID));
				if ($uid < 1)
				{
					$uid = MEMBER_ID;
				}

				if($uid==MEMBER_ID)
				{
					$_my = $GLOBALS['_J']['member'];
				}
				else
				{
					if($uid > 0)
					{
						$query = $this->DatabaseHandler->Query("select `uid`,`theme_id`,`theme_bg_image`,`theme_bg_color`,`theme_text_color`,`theme_link_color`,`theme_bg_image_type`,`theme_bg_repeat`,`theme_bg_fixed` from ".TABLE_PREFIX."members where `uid`='".$uid."'");
						$_my = $query->GetRow();
					}
				}
			}

			if ($_my && $_my['theme_id'])
			{
				$this->Config['theme_id'] = $_my['theme_id'];
				$this->Config['theme_bg_image'] = $_my['theme_bg_image'];
				$this->Config['theme_bg_color'] = $_my['theme_bg_color'];
				$this->Config['theme_text_color'] = $_my['theme_text_color'];
				$this->Config['theme_link_color'] = $_my['theme_link_color'];

				$this->Config['theme_bg_image_type'] = $_my['theme_bg_image_type'];
				$this->Config['theme_bg_repeat'] = $_my['theme_bg_repeat'];
				$this->Config['theme_bg_fixed'] = $_my['theme_bg_fixed'];
			}
		}


		if($this->Config['theme_bg_image'] && false===strpos($this->Config['theme_bg_image'],':/'.'/'))
		{
			$this->Config['theme_bg_image'] = ($this->Config['site_url'] . '/' . $this->Config['theme_bg_image']);



			$this->Config['theme_bg_repeat'] = ($this->Config['theme_bg_repeat'] ? 'repeat' : 'no-repeat');
			$this->Config['theme_bg_fixed'] = ($this->Config['theme_bg_fixed'] ? 'fixed' : 'scroll');
		}
		$this->Config['theme_bg_image_type'] = ($this->Config['theme_id'] ? $this->Config['theme_bg_image_type'] : "");
		if($this->Config['theme_bg_image_type'])
		{
			$this->Config['theme_bg_position'] = ($this->Config['theme_bg_image_type'] . ' top');
			if ('repeat'==$this->Config['theme_bg_image_type'])
			{
				$this->Config['theme_bg_position'] = 'left top';
			}

			elseif('repeat'==$this->Config['theme_bg_image_type'])
			{
				$this->Config['theme_bg_position'] = 'left bottom';
			}
			else
			{
				$this->Config['theme_bg_position'] = 'center 0';
			}

		}

	}

	function ShowBody($body)
	{
		echo $body;

		if($this->MemberHandler) {
			$this->MemberHandler->UpdateSessions();
		}

		
	}

	function js_show_msg()
	{
		$return = "{$GLOBALS['schedule_html']}";

		if($GLOBALS['jsg_schedule_mark'] || jsg_getcookie('jsg_schedule'))
		{
			$return .= jsg_schedule();
		}

		if(!$GLOBALS['js_show_msg_executed'] && ($js_show_msg=($GLOBALS['js_show_msg'] ? $GLOBALS['js_show_msg'] : jsg_getcookie('js_show_msg'))))
		{
			$GLOBALS['js_show_msg_executed'] = 1;
			jsg_setcookie('js_show_msg','',-311040000);
			unset($GLOBALS['js_show_msg'],$_COOKIE['js_show_msg']);

			$return .= "<script language='javascript'>
			$(document).ready(function(){show_message('{$js_show_msg}');});
			</script>";
		}

		return $return;
	}


	function oldhookscript($script ='', $type = 'funcs')
	{
		static $PluginObj;

		$hookall_config = ConfigHandler::get('hookall');

		$hook_return = array();
		if(@is_array($hookall_config))
		{
			foreach($hookall_config as $identifier => $hook_file)
			{
				if(@file_exists($modfile = PLUGIN_DIR .'/'.$hook_file.'.class.php')){

					@include_once PLUGIN_DIR .'/'.$hook_file.'.class.php';

					$class_name = 'plugin_'.$identifier;

					if(!class_exists($class_name)){
						continue;
					}

					if(!isset($PluginObj[$class_name])) {
						$PluginObj[$identifier] = new $class_name;
					}

					$classfunc = get_class_methods($class_name);

					foreach($classfunc as $funcname){

						if(!method_exists($PluginObj[$identifier], $funcname)) {
							continue;
						}

						if($funcname)
						{
							if($PluginObj[$identifier]->$funcname())
							{
								$hook_return[$funcname] .= $PluginObj[$identifier]->$funcname();
							}
						}
					}
				}
			}
		}
		return $hook_return;
	}

	function __is_public() {
		if(!isset($this->__is_public)) {
			$this->__is_public = (($this->Module == 'topic' && $this->Code == 'simple') ||
					($this->Module == 'other' && $this->Code == 'notice') ||
					in_array($this->Module, array('member','login','get_password')));
		}
		return $this->__is_public;
	}

	function __init_code() {
		$jcode = jget('code');
		$morg = ($_POST['mod_original'] ? $_POST['mod_original'] : $_GET['mod_original']);
		$_GET['code'] = $_POST['code'] = $this->Code = (MEMBER_ID > 0 || $morg) ? $jcode :
		($jcode ? $jcode :
				(isset($this->Config['default_code']) ? $this->Config['default_code'] : 'normal'));
		return $_GET['code'];
	}


	/**
	 * GX json返回数据
	 * @param unknown_type $data
	 */
	function ajaxReturn($data){
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($data));
	}

	/**
	 * GX错误
	 * @param unknown_type $msg
	 * @param unknown_type $url
	 */
	function err($msg,$url=""){
		$data["info"]=$msg;
		$data["url"]=$url;
		$data["status"]=0;
		self::ajaxReturn($data);
	}
	/**
	 * GX成功
	 * @param unknown_type $msg
	 * @param unknown_type $url
	 */
	function succ($msg,$url=""){
		$data["info"]=$msg;
		$data["url"]=$url;
		$data["status"]=1;
		self::ajaxReturn($data);
	}


}
?>